package cxt.com.recyclerview.demo5;

import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.View;

/**
 * 作者：chengxiangtong on 2017/1/10 14:41
 * 邮箱：528440900@qq.com
 */

public class EmptyRecycleView extends RecyclerView {

    private View mEmptyView;


    private AdapterDataObserver mObserver = new AdapterDataObserver() {
        @Override
        public void onChanged() {
            Adapter adapter = getAdapter();
            if (adapter.getItemCount() == 0) {
                mEmptyView.setVisibility(VISIBLE);
                EmptyRecycleView.this.setVisibility(GONE);
            } else {
                mEmptyView.setVisibility(GONE);
                EmptyRecycleView.this.setVisibility(VISIBLE);
            }
        }


        @Override
        public void onItemRangeChanged(int positionStart, int itemCount) {
            onChanged();
        }

        @Override
        public void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) {
            onChanged();
        }


        @Override
        public void onItemRangeRemoved(int positionStart, int itemCount) {
            onChanged();
        }

        @Override
        public void onItemRangeChanged(int positionStart, int itemCount, Object payload) {
            onChanged();
        }

        @Override
        public void onItemRangeInserted(int positionStart, int itemCount) {
            onChanged();
        }
    };

    public EmptyRecycleView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public void setmEmptyView(View mView) {
        mEmptyView = mView;
    }

    public void setAdapter(RecyclerView.Adapter mAdapter) {
        super.setAdapter(mAdapter);
        mAdapter.registerAdapterDataObserver(mObserver);
        mObserver.onChanged();
    }

}
